#include "toy_manager.h"
#include <algorithm>

ToyManager::ToyManager(const std::string& filename) 
    : persistence(filename) {
    toys = persistence.loadToys();
}

void ToyManager::createToy(const Toy& toy) {
    toys.push_back(toy);
    saveChanges();
}

Toy* ToyManager::readToy(int id) {
    auto it = std::find_if(toys.begin(), toys.end(), 
        [id](const Toy& t) { return t.getId() == id; });
    return it != toys.end() ? &(*it) : nullptr;
}

void ToyManager::updateToy(int id, const Toy& newToy) {
    auto it = std::find_if(toys.begin(), toys.end(),
        [id](const Toy& t) { return t.getId() == id; });
    if (it != toys.end()) {
        *it = newToy;
        saveChanges();
    }
}

void ToyManager::deleteToy(int id) {
    toys.erase(std::remove_if(toys.begin(), toys.end(),
        [id](const Toy& t) { return t.getId() == id; }), toys.end());
    saveChanges();
}

void ToyManager::displayAllToys() {
    for (const auto& toy : toys) {
        toy.displayInfo();
    }
}

std::vector<Toy> ToyManager::searchToys(const std::string& keyword) {
    std::vector<Toy> results;
    
    // 遍历所有玩具
    for (const auto& toy : toys) {
        // 检查玩具名称或类型是否包含关键词
        if (toy.getName().find(keyword) != std::string::npos ||
            toy.getType().find(keyword) != std::string::npos) {
            results.push_back(toy);
        }
    }
    
    return results;
}

void ToyManager::saveChanges() {
    persistence.saveToys(toys);
}    